package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 批量添加
     *
     * @param list
     */
    public void add(List<OrderSetting> list) {
        if (list != null & list.size() > 0) {
            for (OrderSetting orderSetting : list) {
                //检查次数据（日期）是否存在
                long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if (count > 0) {
                    //已经存在，执行更新操作
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                } else {
                    //不存在  执行添加操作
                    orderSettingDao.add(orderSetting);
                }

            }
        }
    }

    /**
     * 根据月份查询对应的预约设置
     *
     * @param date
     * @return
     */
    public List<Map> getOrderSettingByMonth(String date) {
        //date=2020-2
        //数据库date格式为2020-2-1
        String start = date + "-1";//2020-2-1
        String end = date + "-31";//2020-2-31
        //封装为map集合  便于
        Map map = new HashMap();
        map.put("start", start);
        map.put("end", end);
        //根据数据库里面的日期格式进行查询
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);
        //查询出来的结果和页面显示的数据格式有差异  先格式转换
        List<Map> data = new ArrayList<Map>();
        for (OrderSetting orderSetting : list) {
            Map orderSettingMap = new HashMap();
            orderSettingMap.put("date", orderSetting.getOrderDate().getDate());
            orderSettingMap.put("number", orderSetting.getNumber());
            orderSettingMap.put("reservations", orderSetting.getReservations());
            data.add(orderSettingMap);
        }
        return data;
    }

    /**
     * 根据日期修改预约人数
     *
     * @param orderSetting
     */
    public void editNumberByDate(OrderSetting orderSetting) {
        //分两种情况  如果已经有值 执行更新操作 反之则执行添加操作
        long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (count > 0) {
            //执行更新
            orderSettingDao.editNumberByOrderDate(orderSetting);
        } else {
            //添加操作
            orderSettingDao.add(orderSetting);
        }
    }


}
